import Taro from '@tarojs/taro';
import { isWeapp, isAlipay } from '@/base/env';

/**
 * 一键登录获取code
 */
export async function setAuthCode() {
  if (isWeapp) {
    const res = await Taro.login();
    const response = { data: { data: { authorize: res.code } } };

    if (response.data.data && response.data.data.authorize) {
      const wechatAuthorize = response.data.data.authorize;

      Taro.setStorageSync('authorize', wechatAuthorize);
    } else {
      console.log('获取code失败');
    }
  }

  if (isAlipay) {
    const res = my.getAuthCode();

    if (res) {
      const { authCode } = res;

      Taro.setStorageSync('authorize', authCode);
    } else {
      console.log('获取code失败');
    }
  }
}

/**
 * 读取授权code
 */
export function getAuthCode() {
  return Taro.getStorageSync('authorize');
}
